﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WSS.hameduconn.Bases;
using BussinessLogic;
using DataAccess;

namespace WSS.hameduconn
{
    public partial class Account : BasePage
    {
        private static int CurrentPage = 0;
        private static int CurrentSize = 20;
        private static int TotalPages = 0;
        private static int CurrentId = int.MinValue;
        BLUser userControls;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsAuthenticated || AuthenticateInfo.admin == null)
                Response.Redirect(ResolveUrl("~/Login.aspx"));

            userControls = new BLUser();
            if (!IsPostBack)
            {
                btnBack.Visible = false;
                memberUsers.Visible = true;
                memberSection.Visible = false;
                divAlert.Visible = false;
                LoadList();
            }

        }

        private void LoadList()
        {
            if (!String.IsNullOrEmpty(Request.QueryString["p"]))
            {
                bool result = int.TryParse(Request.QueryString["p"], out CurrentPage);
                if (result == false)
                {
                    CurrentPage = 0;
                }
                else
                {
                    CurrentPage--;
                }
            }
            var lstUser = userControls.GetUsers(CurrentPage, CurrentSize, out TotalPages);
            grdViewMemberHistory.DataSource = lstUser;
            grdViewMemberHistory.DataBind();
            divPaging.InnerHtml = RenderPaging(CurrentPage);
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            memberUsers.Visible = false;
            memberSection.Visible = true;
            btnBack.Visible = true;
            btnAdd.Visible = false;
            btnRegister.Visible = true;
            btnUpdate.Visible = false;
            divAlert.Visible = false;
            tbPassword.Enabled = true;
            tbConfirmPassword.Enabled = true;
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            memberUsers.Visible = true;
            memberSection.Visible = false;
            btnAdd.Visible = true;
            divAlert.Visible = false;
            btnBack.Visible = false;
            ClearText();
        }

        protected void ibtEdit_Command(object sender, CommandEventArgs e)
        {
            int userId = int.Parse(e.CommandArgument.ToString());
            User user = userControls.GetUser(userId);
            if (user != null)
            {
                tbCity.Text = user.City;
                tbConfirmPassword.Text = new AUEncrypt().Decrypt(user.Password);
                tbCreditNo.Text = user.CreditCardNo;
                tbCVS.Text = user.CVS;
                tbEmail.Text = user.Email;
                tbExpirationDate.Text = user.ExpDate != null ? user.ExpDate.Value.ToString("MM/dd/yyyy") : "";
                tbFirstName.Text = user.Firstname;
                tbLastName.Text = user.Lastname;
                tbPassword.Text = new AUEncrypt().Decrypt(user.Password);
                tbState.Text = user.State;
                tbStreet.Text = user.Street;
                tbUsername.Text = user.Username;
                tbZipcode.Text = user.Zipcode;
                CurrentId = user.Id;

                memberSection.Visible = true;
                memberUsers.Visible = false;
                btnAdd.Visible = false;
                btnBack.Visible = true;
                btnRegister.Visible = false;
                btnUpdate.Visible = true;
                divAlert.Visible = false;
            }
            else
            {
                AlertWarning("Error");
                return;
            }
        }

        protected void grdViewMemberHistory_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                User n = (User)e.Row.DataItem;

                Label lblNo = (Label)e.Row.FindControl("lblNo");
                lblNo.Text = Convert.ToString(CurrentPage * CurrentSize + e.Row.RowIndex + 1);

                Label lblExpirationDate = (Label)e.Row.FindControl("lblExpirationDate");
                lblExpirationDate.Text = n.ExpDate == null ? "" : n.ExpDate.Value.ToString("MM/dd/yyyy");

            }
        }

        protected string RenderPaging(int current)
        {
            if (current > TotalPages)
            {
                return "";
            }
            string html = "<ul class=\"pagination\">";

            if (current == 0)
            {
                html +=
                    "<li class=\"first disabled\"><a href=\"#\"><< First</a></li>" +
                        "<li class=\"prev disabled\"><a href=\"#\">< Prev</a></li>";
            }
            else
            {
                html += "<li class=\"first\"><a href=\"" + ResolveUrl("~/Register.aspx?p=" + 1) + "\"><< First</a></li>" +
                        "<li class=\"prev\"><a href=\"" + ResolveUrl("~/Register.aspx?&p=" + current) + "\">< Previous</a></li>";
            }

            for (int i = 1; i <= TotalPages; i++)
            {
                if (current == (i - 1))
                {
                    html += "<li class=\"active\"><a href=\"#\">" + i + "</a></li>";
                }
                else
                {
                    html += "<li><a href='" + ResolveUrl("~/Register.aspx&p=" + i) + "'>" + i + "</a></li>";
                }
            }

            if (current < (TotalPages - 1))
            {
                html += "<li class=\"next\"><a href=\"" + ResolveUrl("~/Register.aspx&p=" + (current + 2)) + "\">Next ></a></li>" +
                        "<li class=\"last\"><a href=\"" + ResolveUrl("~/Register.aspx&p=" + TotalPages) + "\">Last >></a></li>";
            }
            else
            {
                html += "<li class=\"next disabled\"><a href=\"#\">Next ></a></li>" +
                        "<li class=\"last disabled\"><a href=\"#\">Last >></a></li>";
            }
            html += "</ul>";
            return html;
        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {
            string city = tbCity.Text;
            string creditCard = tbCreditNo.Text;
            string cvs = tbCVS.Text;
            string email = tbEmail.Text;
            string expDate = tbExpirationDate.Text;
            string fName = tbFirstName.Text;
            string lName = tbLastName.Text;
            string passWord = tbPassword.Text;
            string confirmPassWord = tbConfirmPassword.Text;
            string state = tbState.Text; string street = tbStreet.Text;
            string username = tbUsername.Text;
            string zipCode = tbZipcode.Text;

            if (string.IsNullOrEmpty(username))
            {
                AlertWarning("Please input require field");
                return;
            }

            if (passWord != confirmPassWord)
            {
                AlertWarning("Confirm password incorrect");
                return;
            }

            if (!string.IsNullOrEmpty(email) && !Utilities.IsValidEmail(email))
            {
                AlertWarning("Wrong email syntax");
                return;
            }

            if (!userControls.CheckUser(username))
            {
                AlertWarning("Username is exist");
                return;
            }

            DateTime? date = null;
            User user = new User
            {
                City = city,
                CreditCardNo = creditCard,
                CVS = cvs,
                Email = email,
                ExpDate = string.IsNullOrEmpty(expDate) ? date : DateTime.Parse(expDate),
                Firstname = fName,
                Lastname = lName,
                Password = new AUEncrypt().Encrypt(passWord),
                State = state,
                Street = street,
                Username = username,
                Zipcode = zipCode,
            };

            if (userControls.CreatUser(ref user))
            {
                AlertSuccess("Create new user success !");
                memberSection.Visible = false;
                memberUsers.Visible = true;
                btnAdd.Visible = true;
                LoadList();
                ClearText();
            }
            else
            {
                AlertError("Create new user fail!");
            }
        }
     
        protected void AlertWarning(string msg)
        {
            divAlert.Attributes["class"] = "alert alert-danger";
            divAlert.InnerHtml = msg;
            divAlert.Visible = true;
        }

        protected void AlertError(string msg)
        {
            divAlert.Attributes["class"] = "alert alert-danger";
            divAlert.InnerHtml = msg;
            divAlert.Visible = true;
        }

        protected void AlertSuccess(string msg)
        {
            divAlert.Attributes["class"] = "alert alert-success";
            divAlert.InnerHtml = msg;
            divAlert.Visible = true;
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(hdUserId.Value) || hdUserId.Value == "0")
            {
                return;
            }
            int userId = int.MinValue;
            if (!int.TryParse(hdUserId.Value, out userId))
            {
                return;
            }
            if (userControls.DeleteUser(userId))
            {
                AlertSuccess("Delete user success");
                LoadList();
            }
            else
            {
                AlertError("Delete user fail.");
                return;
            }

        }
        protected void ClearText()
        {
            tbCity.Text = string.Empty;
            tbConfirmPassword.Text = string.Empty;
            tbCreditNo.Text = string.Empty;
            tbCVS.Text = string.Empty;
            tbEmail.Text = string.Empty;
            tbExpirationDate.Text = string.Empty;
            tbFirstName.Text = string.Empty;
            tbLastName.Text = string.Empty;
            tbPassword.Text = string.Empty;
            tbState.Text = string.Empty;
            tbStreet.Text = string.Empty;
            tbUsername.Text = string.Empty;
            tbZipcode.Text = string.Empty;
            CurrentId = int.MinValue;
        }
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            string city = tbCity.Text;
            string creditCard = tbCreditNo.Text;
            string cvs = tbCVS.Text;
            string email = tbEmail.Text;
            string expDate = tbExpirationDate.Text;
            string fName = tbFirstName.Text;
            string lName = tbLastName.Text;
            string state = tbState.Text; string street = tbStreet.Text;
            string username = tbUsername.Text;
            string zipCode = tbZipcode.Text;

            if (string.IsNullOrEmpty(username))
            {
                AlertWarning("Please input require field");
                return;
            }

            if (!string.IsNullOrEmpty(email) && !Utilities.IsValidEmail(email))
            {
                AlertWarning("Wrong email syntax");
                return;
            }

            DateTime? date = null;
            User user = new User
            {
                Id = CurrentId,
                City = city,
                CreditCardNo = creditCard,
                CVS = cvs,
                Email = email,
                ExpDate = string.IsNullOrEmpty(expDate) ? date : DateTime.Parse(expDate),
                Firstname = fName,
                Lastname = lName,
                Password = null,
                State = state,
                Street = street,
                Username = username,
                Zipcode = zipCode,
            };

            if (userControls.Update(user))
            {
                AlertSuccess("Update user success !");
                memberSection.Visible = false;
                memberUsers.Visible = true;
                btnAdd.Visible = true;
                btnBack.Visible = false;
                LoadList();
                ClearText();
            }
            else
            {
                AlertError("Update user fail!");
            }
        }
    }
}